<template>
  <div ref="chartContainer" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from "vue";
import * as echarts from "echarts"; // 引入 echarts 库

const props = defineProps({
  xData: {
    type: Array,
    required: true,
  },
  dayTemps: {
    type: Array,
    required: true,
  },
  nightTemps: {
    type: Array,
    required: true,
  },
});

const chartContainer = ref(null); // 用于引用 DOM 元素

// 图表实例
let chartInstance = null;

// 图表的选项状态
const option = ref({});

// 更新图表的函数
const renderChart = (xData, dayTemps, nightTemps) => {
  if (!chartInstance) return;

  option.value = {
    xAxis: {
      type: "category",
      data: xData,
      show: false,
    },
    grid: {
      left: "10%", // 左边距
      right: "10%", // 右边距
      top: "20%", // 上边距
      bottom: "20%", // 下边距
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        name: "白天气温",
        type: "line",
        data: dayTemps,
        label: {
          show: true,
          position: "top",
          formatter: (params) => `白 ${params.value}℃`, // 在白天气温的标签前加上“白”字
          color: "white", // 设置白天气温注释为黑色
        },
      },
      {
        name: "夜间气温",
        type: "line",
        data: nightTemps,
        label: {
          show: true,
          position: "top",
          formatter: (params) => `晚 ${params.value}℃`, // 在夜间气温的标签前加上“晚”字
          color: "white", // 设置夜间气温注释为黑色
        },
      },
    ],
  };

  chartInstance.setOption(option.value); // 设置图表配置
};

// 在组件挂载后初始化图表
onMounted(() => {
  nextTick(() => {
    chartInstance = echarts.init(chartContainer.value); // 初始化 ECharts 实例
    renderChart(props.xData, props.dayTemps, props.nightTemps); // 初次渲染
  });
});

// 监听数据变化，更新图表选项
watch(
  [() => props.xData, () => props.dayTemps, () => props.nightTemps],
  () => {
    renderChart(props.xData, props.dayTemps, props.nightTemps);
  },
  { immediate: true }
);
</script>

